import { injectable, inject } from 'inversify'
import { PrismaDB } from '../../db';

import {UserDTO} from './user.dto'
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';

import { JWT } from '../../jwt';
import { User } from './controller';

@injectable()
export class UserService {
    constructor(
        @inject(PrismaDB) private readonly prismaDB: PrismaDB
       ,@inject(JWT) private readonly JWT: JWT
    ) { }
    public async getUser() {
        return await this.prismaDB.prisma.user.findMany()

    }

    public async getUserToken() {
        return await this.prismaDB.prisma.user.findMany()

    }

    public async createUser(user : UserDTO) {
        let userDto = plainToClass(UserDTO, user)//把user值返回给userDTO类型(把前端传的值合并到类里面然后传给userDto) 方便进行验证
        const errors = await validate(userDto)
        if (errors.length > 0) { //如果是个数组，说明传参有问题
            return errors
        }else{
            return await this.prismaDB.prisma.user.create({ data : user })
        }
    }

    public async loginUser(user : UserDTO) {
        let userDto = plainToClass(UserDTO, user)//把user值返回给userDTO类型(把前端传的值合并到类里面然后传给userDto) 方便进行验证
        const errors = await validate(userDto)
        if (errors.length > 0) { //如果是个数组，说明传参有问题
            return errors
        }else{
           let result = await this.prismaDB.prisma.user.findFirst({
              where: {
                  email: user.email,
                  name: user.name
              }
           })
           return {
              ...result,
              token: this.JWT.createToken(result)//生成token,result是载荷
           }
        }
    }
}